package com.ergou.easylive.admin.controller.common;

import com.ergou.easylive.admin.annotation.AccessLog;
import com.ergou.easylive.admin.constants.CaptchaConstants;
import com.ergou.easylive.admin.entity.vo.CaptchaVO;
import com.ergou.easylive.common.entity.response.Result;
import com.ergou.easylive.admin.exception.SystemException;
import com.ergou.easylive.common.enums.ResultCode;
import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * 获取验证码
 *
 * @author Er-Gou
 * @date 2025-10-02 14:45
 * @description: 验证码
 */
@RestController
@RequestMapping
@Slf4j
@Tag(name = "公共接口", description = "验证码、文件上传等公共功能接口")
public class CaptchaController {

    @Resource(name = "charCaptcha")
    private Producer kaptchaProducer;

    @Resource
    private CacheManager cacheManager;

    @GetMapping("/captcha/image")
    @Operation(summary = "获取验证码图片")
    @AccessLog(value = "获取验证码图片")
    public Result<CaptchaVO> captchaImage() {
        CaptchaVO captchaVO = new CaptchaVO();

        // 生成文字验证码
        String text = kaptchaProducer.createText();
        log.info("code:{}", text);
        // 生成图片验证码
        BufferedImage image = kaptchaProducer.createImage(text);

        String uuid = UUID.randomUUID().toString();

        // 1.将文字验证码存入 本地缓存
        String prefixKey = CaptchaConstants.SYS_CAPTCHA_CODE_KEY + uuid;
        log.info("prefixKey:{}", prefixKey);

        // 存储验证码到缓存
        Cache cache = cacheManager.getCache("captcha");
        if (cache != null) {
            cache.put(prefixKey, text);
        }

        // 2.将图片转换成base64
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new SystemException(ResultCode.INTERNAL_SERVER_ERROR, "验证码图片生成失败");
        }
        // 3.将uuid返回给前端
        captchaVO.setCaptchaId(uuid);
        captchaVO.setCaptchaImage(Base64.getEncoder().encodeToString(os.toByteArray()));

        return Result.success(captchaVO);
    }

}
